package com.rj.data.config;

import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;

import javax.net.ssl.SSLContext;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;

public class JestFactory {


    private static JestClient jestClient;

    static {
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig
                .Builder(Arrays.asList("http://10.6.0.1:9200",
                "http://10.6.0.2:9200",
                "http://10.6.0.3:9200"))
                .defaultCredentials("elastic", "vnLaQc8tV1goibFte21m")
//                .Builder("http://45.119.104.34:9201")//.defaultCredentials("admin","admin")
                //.sslSocketFactory(getSslSockedFactory())
                .connTimeout(600000)
                .readTimeout(600000)
                .defaultMaxTotalConnectionPerRoute(Integer.valueOf(60000))
                .maxTotalConnection(Integer.valueOf(60000))
                .multiThreaded(true)
                .build());
        jestClient = factory.getObject();
    }

    private static SSLConnectionSocketFactory getSslSockedFactory() {
        SSLContextBuilder builder = SSLContexts.custom();
        SSLContext sslcontext = null;
        try {
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            });
            sslcontext = builder.build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
        return sslsf;
    }

    public static JestClient getJestClient() {
        return jestClient;
    }
}
